package com.jasperframework.boot.common.utils.xss;

import org.springframework.web.util.HtmlUtils;

import java.util.regex.Pattern;

/**
 * 工具类XssUtils
 * 现在的做法是替换成空字符，CSDN的是进行转义，比如文字开头的"<"转成&lt;
 * 防止脚本注入攻击
 */
public class XssUtils {

    private static final Pattern[] patterns = new Pattern[]{
        // Script fragments
        Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
        Pattern.compile("src[\r\n]*=[\r\n]*\\'(.*?)\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
        Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        Pattern.compile("e­xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
        Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
        Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
    };

    /**
     * 综合 XSS 防护方法
     *
     * @param value 输入字符串
     * @return 防护后的字符串
     */
    public static String sanitize(String value) {
        if (value == null) {
            return null;
        }

        // 使用正则表达式移除潜在的 XSS 代码
        for (Pattern scriptPattern : patterns) {
            value = scriptPattern.matcher(value).replaceAll("");
        }

        // HTML 转义，防止 HTML 注入
        return HtmlUtils.htmlEscape(value); // 或 StringEscapeUtils.escapeHtml4(value)
    }

    public static void main(String[] args) {
        String s = sanitize("<img  src=x onload=alert(111).*?><script></script>javascript:eval()\\\\.");
        System.err.println("s======>" + s);
    }
}
